<?php
class ModelShippingPacsoft extends Model {
	function getQuote($address) {
		$this->load->language('shipping/pacsoft');

        if ($this->config->get('pacsoft_status')) {
            /*
            $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('pacsoft_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");

            if (!$this->config->get('pacsoft_geo_zone_id')) {
                $status = true;
            } elseif ($query->num_rows) {
                $status = true;
            } else {
                $status = false;
            }
            */

            $status = true;
        }
        else {
            $status = false;
        }

		$method_data = array();
	
		if ($status) {
			$this->load->model('localisation/country');
			$country_info = $this->model_localisation_country->getCountry($address['country_id']);

            $postcode = str_replace(' ', '', $address['postcode']);
            $cost = $this->config->get('pacsoft_cost');
            $tax_class = $this->config->get('pacsoft_tax_class_id');
            $error_msg = '';
            $quote_data = array();

            $result = $this->loadPacsoft($postcode, $country_info['iso_code_2']);
            if(!empty($result)){
                foreach($result as $item) {
                    $quote_data[$item['code']] = array(
                        'id'           => 'pacsoft.'.$item['code'],
                        'code'         => 'pacsoft.'.$item['code'],
                        'title'        => $item['title'],
                        'cost'         => $cost,
                        'tax_class_id' => $tax_class,
                        'text'         => $this->currency->formatPrice($this->tax->calculate($cost, $tax_class, $this->config->get('config_tax')))
                    );
                }
            }
            else {
                $error_msg = $this->language->get('text_error');
            }
			
			$title = $this->language->get('text_title');
			$method_data = array(
				'code'       => 'pacsoft',
				'title'      => $title,
				'quote'      => $quote_data,
				'sort_order' => $this->config->get('pacsoft_sort_order'),
				'error'      => $error_msg
			);
			
		}

		return $method_data;
	}

    private function loadPacsoft($postcode, $country_code){
        //$url = 'http://api.postnord.com/wsp/rest/BusinessLocationLocator/Logistics/ServicePointService_1.0/findNearestByAddress.xml?consumerId='.$this->config->get('pacsoft_key').'&countryCode='.$country_code.'&postalCode='.$postcode;
        $url = 'http://api.postnord.com/wsp/rest/BusinessLocationLocator/Logistics/ServicePointService_1.0/findNearestByAddress.json?consumerId='.$this->config->get('pacsoft_key').'&countryCode='.$country_code.'&postalCode='.$postcode;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);


        //$result = file_get_contents($url);
        $result = str_replace("\r\n", '', $result);

        $pacsoft_list = array();
        if($result){
            //$pacsoft_list = $this->processXmlData($result);
            $pacsoft_list = $this->processJsonData($result);
        }

        return $pacsoft_list;
    }

    private function processXmlData($data){
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->loadXml($data);

        $result = array();
        $service_response = $dom->getElementsByTagName('servicePointInformationResponse')->item(0);
        $shipment_response = $service_response->getElementsByTagName('servicePoints')->item(0);
        $shipments = $shipment_response->getElementsByTagName('servicePoint');
        if($shipments->length > 0){
            foreach($shipments as $shipment) {
                $service = $shipment->getElementsByTagName('name')->item(0)->nodeValue;
                $code = $shipment->getElementsByTagName('servicePointId')->item(0)->nodeValue;

                $visit_address = $shipment->getElementsByTagName('deliveryAddress')->item(0);
                $delivery_address = $shipment->getElementsByTagName('deliveryAddress')->item(0);
                $street1 = $visit_address->getElementsByTagName('streetName')->item(0)->nodeValue;
                $street2 = $delivery_address->getElementsByTagName('streetName')->item(0)->nodeValue;
                $zipcode1 = $visit_address->getElementsByTagName('postalCode')->item(0)->nodeValue;
                $zipcode2 = $delivery_address->getElementsByTagName('postalCode')->item(0)->nodeValue;
                $city1 = ucfirst(mb_strtolower($visit_address->getElementsByTagName('city')->item(0)->nodeValue));  //ucfirst(mb_strtolower($shipment->getElementsByTagName('city')->item(0)->nodeValue));
                $city2 = ucfirst(mb_strtolower($delivery_address->getElementsByTagName('city')->item(0)->nodeValue));

                $result[]   = array(
                    'code'         => 'pacsoft_'.trim($code),
                    'title'        => trim($service).", ".trim($street1).", ".trim($zipcode1)." ".trim($city1),
                );
            }
        }

        return $result;
    }

    private function processJsonData($data){
        $result = array();
        $service_response = json_decode($data);

        if($service_response->servicePointInformationResponse){
            $shipments = $service_response->servicePointInformationResponse->servicePoints;
            foreach($shipments as $shipment) {
                $service = $shipment->name;
                $code = $shipment->servicePointId;

                $visit_address = $shipment->visitingAddress;
                $delivery_address = $shipment->deliveryAddress;
                $street1 = $visit_address->streetName;
                $street2 = $delivery_address->streetName;
                $zipcode1 = $visit_address->postalCode;
                $zipcode2 = $delivery_address->postalCode;
                $city1 = $this->ucfirstUnicode(mb_strtolower($visit_address->city, 'UTF-8'));
                $city2 = $this->ucfirstUnicode(mb_strtolower($delivery_address->city, 'UTF-8'));

                $result[]   = array(
                    'code'         => 'pacsoft_'.trim($code),
                    'title'        => trim($service).", ".trim($street1).", ".trim($zipcode1)." ".trim($city1),
                );
            }
        }

        return $result;
    }

    private function ucfirstUnicode($string){
        $string = mb_strtoupper(mb_substr($string, 0, 1, 'UTF-8'), 'UTF-8') . mb_substr($string, 1, 'UTF-8');

        return $string;
    }
}